package com.bh.common.utils;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.bh.common.config.ALiYunSMSConfig;
import com.bh.common.constant.CacheConstants;
import com.bh.common.constant.SmsConstants;
import com.bh.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * sms
 *
 * @author shuangluxing@163.com
 * @date 2023/03/14
 */
@Configuration
@Component
public class SmsConfigUtils {
    private static final Logger log = LoggerFactory.getLogger(SmsConfigUtils.class);
    /**
     * 短信签名名称
     */
    @Value("${aliyun.sms.signName}")
    private String signName;

    @Autowired
    ALiYunSMSConfig aLiYunSMSConfig;

    @Autowired
    private RedisCache redisCache;


    /**
     * 发送短消息
     *
     * @param sendSmsRequest 发送短信请求
     * @return {@link SendSmsResponse}
     * @throws Exception 异常
     *//*
     * @version V1.0
     * Title: sendShortMessage
     * @author Wangwei
     * @description 发送短信
     * @createTime  2022/11/7 16:02
     * @param [sendSmsRequest]
     * @return com.aliyun.dysmsapi20170525.models.SendSmsResponse
     */
    public SendSmsResponse sendShortMessage(SendSmsRequest sendSmsRequest) throws Exception {
        //初始化配置信息
        Client client = aLiYunSMSConfig.createClient();
        //TODO 配置运行时间选项暂时未进行配置
        RuntimeOptions runtime = new RuntimeOptions();

        SendSmsResponse sendSmsResponse;
        try {
            //发送短信
            sendSmsRequest.setSignName(signName);
            sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception e) {
            throw new Exception("调用发送短信接口失败", e);
        }
        log.info("调用发送短信接口成功");
        return sendSmsResponse;
    }

    /**
     * 发送验证码，短信模板Code 固定
     * @param phoneNumber
     * @return
     * @throws Exception
     */
    public boolean sendCode(String phoneNumber) throws Exception {
        //生成六位手机验证码
        String verificationCode = randomCode(phoneNumber);
        //拼接短信模板变量对应的实际值"{\"code\":\"+verificationCode+\"}";
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("code", verificationCode);
        String templateParam = JSON.toJSONString(hashMap);
        //配置发送短信的请求体
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        //设置短信模板Code
        sendSmsRequest.setTemplateCode(SmsConstants.CACHE_TEMPLATE_CODE_1);
        //设置发送短信的手机号
        sendSmsRequest.setPhoneNumbers(phoneNumber);
        //设置短信模板变量对应的实际值
        sendSmsRequest.setTemplateParam(templateParam);
        //发送短信响应体
        SendSmsResponse sendSmsResponse;
        try {
            //调用短信服务发送短信验证码
            sendSmsResponse = sendShortMessage(sendSmsRequest);
            log.info("调用短信服务发送短信验证码");
        } catch (Exception e) {
            throw new Exception("调用短信服务发送短信验证码接口失败！", e);
        }
        if (!"OK".equals(sendSmsResponse.getBody().getCode())) {
            log.error("调用短信服务发送短信验证码失败 {}", sendSmsResponse);
            return false;
        }
        log.info("调用短信服务发送短信验证码成功 {}", sendSmsResponse);

        return false;
    }

    public String randomCode(String phoneNumber) {
        StringBuilder stringBuffer = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuffer.append(random.nextInt(10));
        }
        String code = stringBuffer.toString();
        redisCache.setCacheObject(CacheConstants.CACHE_CODE+"::" + phoneNumber, code, 5, TimeUnit.MINUTES);
        return code;
    }

}
